﻿using System.Net;
using Ding.HttpHelper;
using Ding.HttpHelper.Enum;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Newtonsoft.Json;
using SelfService.HaiTai.Models;
using SelfService.HaiTai.Models.HisOracle;
using SelfService.Model.Interface;
using SelfService.Model.Models;
using TT;
using WalkingTec.Mvvm.Core.Extensions;
using JsonSerializer = System.Text.Json.JsonSerializer;

namespace SelfService.HaiTai;

public class HaiTaiReceiptPrint : IReceiptPrint
{
    private readonly HisContext _context;
    private readonly IOptions<AppSettings> _options;

    public HaiTaiReceiptPrint(HisContext context, IOptions<AppSettings> options)
    {
        _context = context;
        _options = options;
    }
    
    public async Task<ResultDetail<List<ReceiptInfo>>> GetList(IPatient patient)
    {
        if (patient.HisCode.IsNullOrWhiteSpace() && patient.CardNo.IsNullOrWhiteSpace())
        {
            return new ResultDetail<List<ReceiptInfo>>()
            {
                Code = 1,
                Message = "请至少提供PatId|CardNo一种身份凭据",
                Request = JsonSerializer.Serialize(patient)
            };
        }
        var list = await _context.HisReceipts
            .WhereIf(!string.IsNullOrWhiteSpace(patient.HisCode), e => e.PatId == patient.HisCode)
            .WhereIf(!string.IsNullOrWhiteSpace(patient.CardNo), e => e.Jzkh == patient.CardNo)
            .Where(e => e.JsRq != null && e.JsRq > DateTime.Now.AddMonths(-3) && e.JsZje > 0)
            .OrderByDescending(e => e.JsRq)
            .Select(e => new ReceiptInfo
            {
                PatientId = e.PatId,
                PatientName = e.PatName,
                Amount = e.JsZje != null ? decimal.Round(decimal.Parse(e.JsZje.ToString()), 2) : 0,
                TradeDate = e.JsRq.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                TradeNo = e.JslshId,
                Type = e.MzZyFlag == "M" ? HisReceiptType.门诊 : HisReceiptType.住院,
                PdfUrl = e.Nwpdf
            })
            .ToListAsync();
        return new ResultDetail<List<ReceiptInfo>>()
        {
            Data = list,
            Request = JsonSerializer.Serialize(patient),
            Response = ""
        };
    }

    public async Task<ResultDetail<ReceiptInfo>> GetDetail(string tradeNo)
    {
        if (tradeNo.IsNullOrWhiteSpace())
        {
            return new ResultDetail<ReceiptInfo>()
            {
                Code = 1,
                Message = "结算号不能为空",
                Request = "tradeNo: " + tradeNo
            };
        }

        var data = await _context
            .HisReceipts
            .AsNoTracking()
            .Where(e => e.JslshId == tradeNo && e.JsRq != null)
            .Select(e => new ReceiptInfo
            {
                PatientId = e.PatId,
                PatientName = e.PatName,
                Amount = e.JsZje != null ? decimal.Round(decimal.Parse(e.JsZje.ToString()), 2) : 0,
                TradeDate = e.JsRq.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                TradeNo = e.JslshId,
                Type = e.MzZyFlag == "M" ? HisReceiptType.门诊 : HisReceiptType.住院,
                PdfUrl = e.Nwpdf
            })
            .FirstOrDefaultAsync();
        if (data == null)
        {
            return new ResultDetail<ReceiptInfo>()
            {
                Code = 1,
                Message = "未找到该结算号"
            };
        }

        if (!data.PdfUrl.IsNullOrWhiteSpace() && data.PdfUrl.StartsWith("http"))
        {
            return new ResultDetail<ReceiptInfo>
            {
                Data = data
            };
        }

        var postData = new
        {
            type = data.Type == HisReceiptType.门诊 ? "M" : "B",
            jslsh_id = data.TradeNo
        };
        //获取PDF信息
        var httpItem = new HttpItem();
        httpItem.URL = $"{_options.Value.HisReceiptUrl}/ld/common/dict/pjsc?method=UploadPj";
        httpItem.Method = "POST";
        httpItem.ContentType = "application/json";
        httpItem.ResultType = ResultType.StringByte;
        httpItem.Postdata = JsonConvert.SerializeObject(postData);
        var httpResult = new HttpHelper().GetHtml(httpItem);
        if (httpResult.StatusCode != HttpStatusCode.OK)
        {
            return new ResultDetail<ReceiptInfo>()
            {
                Code = 1,
                Message = "HIS电子发票服务连接失败, 请联系管理员"
            };
        }
        if (httpResult.Html.Contains("DZPJ_SUC"))
        {
            data = await _context
                .HisReceipts
                .AsNoTracking()
                .Where(e => e.JslshId == tradeNo && e.JsRq != null)
                .Select(e => new ReceiptInfo
                {
                    PatientId = e.PatId,
                    PatientName = e.PatName,
                    Amount = e.JsZje != null ? decimal.Round(decimal.Parse(e.JsZje.ToString()), 2) : 0,
                    TradeDate = e.JsRq.Value.ToString("yyyy-MM-dd HH:mm:ss"),
                    TradeNo = e.JslshId,
                    Type = e.MzZyFlag == "M" ? HisReceiptType.住院 : HisReceiptType.门诊,
                    PdfUrl = e.Nwpdf
                })
                .FirstOrDefaultAsync();
            if (!data.PdfUrl.IsNullOrWhiteSpace() && data.PdfUrl.StartsWith("http"))
            {
                return new ResultDetail<ReceiptInfo>
                {
                    Data = data
                };
            }

            return new ResultDetail<ReceiptInfo>()
            {
                Code = 1,
                Message = "电子发票更新成功, 但是没有找到记录, 请联系HIS工程师"
            };
        }

        return new ResultDetail<ReceiptInfo>()
        {
            Code = 1,
            Message = "电子发票更新失败, 请联系HIS工程师"
        };
    }
}